import React, { useEffect, useState } from 'react'
import DetailContainer from '@/components/DetailContainer'
import Descriptions from '@/components/Descriptions'
import { Button, Checkbox, DatePicker, Empty, Form, InputNumber, message, Select, Space, Typography } from 'antd'
import { EditFormInline, EditFormVertical } from '@/components/CustomForm'
import { useFormBase, useFormInfo } from '../useFormEdit'
import { useForm } from 'antd/es/form/Form'
import { addSupplier, editSupplier, getDetailInfos } from '@/api/supplier'
import { useNavigate, useSearchParams } from 'react-router-dom'
import UploadFile from '@/components/UploadFile'
import { useAppSelector } from '@/store/hooks'
import { CooperateStatusOptions } from '@/constant/supplier'
import { getProductClassConfigByType } from '@/api/goods'
import dayjs from 'dayjs'
import { ITableData } from '../types'
import useGetArea from '@/hooks/useGetArea'
import './FormShare.less'
import { onValuesChange } from '@/utils/onValuesChange'
import { downloadByUrl, getNameByOwnUrl } from '@/utils/util'
import PermissionButton from '@/components/PermissionButton'
import Upload from '@/components/Upload'
import useSearchUser from '@/hooks/useSearchUser'
const Index: React.FC = () => {
  const [FormSupplier] = useForm()
  const [query] = useSearchParams()
  const navigate = useNavigate()
  const [ispedding, setispedding] = useState<boolean>(false)
  const [detailInfo, setdetailInfo] = useState<Record<string, any>>({})
  const supplierId = query.get('supplierId')
  const [classIdOptions, setclassIdOptions] = useState<IOptionItem[]>([])
  const DICTDATA = useAppSelector((state) => state.login.DICTDATA)
  const [areaList, setareaList] = useState<number[]>([])
  const { AreaOptions, loadAreaData } = useGetArea(areaList)
  const cooperateStatus = Form.useWatch('cooperateStatus', FormSupplier)
  const { UserOptions, setUserOptions, handleSearchUser } = useSearchUser('workId')
  // { roleIds: ['62'] }
  //基础信息
  const [isbaseinfoEdit, setisbaseinfoEdit] = useState<boolean>(false)
  const [baseinfoList, setbaseinfoList] = useState<IDesListType>([
    { label: '供应商名称', key: 'supplierName', content: '-' },
    { label: '简称', key: 'supplierShortName', content: '-' },
    { label: '供应商分类', key: 'supplierClassificationCode', content: '-' },
    { label: '采购模式', key: 'purchaseTypeNames', content: '-' },
    { label: '可供应大类', key: 'maiClassCodeName', content: '-' },
    { label: '可供应品类明细', key: 'supplierDetail', content: '-' },
    { label: '区域', key: 'locationCode', content: '-' },
    { label: '引入原因', key: 'useReason', content: '-' },
    {
      label: '开始合作时间',
      key: 'cooperateStartDate',
      content: '-',
      format: (info) => {
        return (info?.cooperateStartDate && dayjs(info?.cooperateStartDate).format('YYYY-MM-DD')) || '-'
      },
    },
    { label: '合作状态', key: 'cooperateStatusName', content: '-' },
    {
      label: '结束合作时间',
      key: 'cooperateEndDate',
      content: '-',
      format: (info) => {
        return (info?.cooperateEndDate && dayjs(info?.cooperateEndDate).format('YYYY-MM-DD')) || '-'
      },
    },
    { label: '供应商评级', key: 'levelCode', content: '-' },
  ])
  //供应商配置
  const [isconfigEdit, setisconfigEdit] = useState<boolean>(false)
  //联络方式
  const [isConcatEdit, setisConcatEdit] = useState<boolean>(false)
  const [concatinfoList, setconcatinfoList] = useState<IDesListType>([
    { label: '联系人', key: 'contactName', content: '-' },
    { label: '联系方式', key: 'contactPhone', content: '-' },
    { label: '供应商联系邮箱', key: 'contactMail', content: '-' },
    { label: '公司法人', key: 'legalPerson', content: '-' },
    { label: '法人电话', key: 'legalContactPhone', content: '-' },
    {
      label: '省市区',
      key: 'aaa',
      content: '-',
      format(detailInfo) {
        return (
          (detailInfo.provinceName ? detailInfo.provinceName : '') +
          (detailInfo.cityName ? '-' + detailInfo.cityName : '') +
          (detailInfo.areaName ? '-' + detailInfo.areaName : '')
        )
      },
    },
    { label: '地址', key: 'contactAddress', content: '-' },
  ])
  //upload
  const [isuploadEdit, setisuploadEdit] = useState<boolean>(false)
  useEffect(() => {
    getProductClassConfig()
    if (supplierId) {
      getDetail()
    } else {
      setisbaseinfoEdit(true)
      setisconfigEdit(true)
      setisConcatEdit(true)
      setisuploadEdit(true)
    }
  }, [])
  const getDetail = async () => {
    const res = await getDetailInfos<ITableData>({ id: supplierId })
    if (res.code === 200) {
      const details = res.data
      setdetailInfo(details)
      details?.supplierCode && (document.title = details.supplierCode)
      handleDetailFactory(baseinfoList, details, setbaseinfoList)
      handleDetailFactory(concatinfoList, details, setconcatinfoList)
      FormSupplier.setFieldsValue({
        ...details,
        cooperateStartDate: details.cooperateStartDate && dayjs(details.cooperateStartDate),
        cooperateEndDate: details.cooperateEndDate && dayjs(details.cooperateEndDate),
        mainClassIds: details.mainClassIds ? details.mainClassIds?.split(',') : [],
        locationCode: details.locationCode,
        contractExpTime: details?.contractExpTime ? dayjs(details?.contractExpTime) : null,
      })
      if (details.returnDayNum != null && details.returnDayNum > 0) {
        FormSupplier.setFieldValue('inStore', true)
      }
      FormSupplier.setFieldValue('returnDayNum', details?.returnDayNum || null)
      // 省市区处理
      if (details.provinceId && details.cityId && details.areaId) {
        const area = [details.provinceId, details.cityId, details.areaId]
        setareaList(area)
        FormSupplier.setFieldValue('area', area)
      }
    }
  }
  const startEdit = async (setisEdit: React.Dispatch<React.SetStateAction<boolean>>) => {
    FormSupplier.validateFields().then(async (data) => {
      console.log(data, 'data')

      setisEdit(true)
      const paramsData = {
        returnDayNum: data?.returnDayNum > 0 ? data?.returnDayNum : 0,
        returnStatusName: data?.returnDayNum > 0 ? '是' : '否',
      }
      Reflect.deleteProperty(data, 'inStore')
      const params = {
        ...detailInfo,
        ...data,
        cooperateStartDate: data.cooperateStartDate && dayjs(data.cooperateStartDate).format('YYYY-MM-DD HH:mm:ss'),
        cooperateEndDate: data.cooperateEndDate
          ? dayjs(data.cooperateEndDate).format('YYYY-MM-DD HH:mm:ss')
          : detailInfo?.cooperateEndDate,
        mainClassIds: data.mainClassIds && data.mainClassIds.join(','),
        qcStatus: data.qcStatus ? 1 : 0,
        scanStatus: data.scanStatus ? 1 : 0,
        autoShipStatus: data.autoShipStatus ? 1 : 0,
        aQuotation: data.aQuotation ? 1 : 0,
        firstOrderMustQuotation: data.firstOrderMustQuotation ? 1 : 0,
        reorderMustQuotation: data.reorderMustQuotation ? 1 : 0,
        settlementUnitPrice: data.settlementUnitPrice ? 1 : 0,
        qcDefaultUserWorkId: data.qcDefaultUserWorkId || null,
        fileId: data.fileId ? data.fileId : '',
        supplierClassificationCodeName: data.supplierClassificationCode,
        supplierClassificationCode: data.supplierClassificationCode,
        provinceId: data?.area?.[0] || detailInfo?.provinceId,
        cityId: data?.area?.[1] || detailInfo?.cityId,
        areaId: data?.area?.[2] || detailInfo?.areaId,
        contractExpTime: data?.contractExpTime ? dayjs(data?.contractExpTime).format('YYYY-MM-DD') : null,
        ...paramsData,
      }
      let res: IResponsePost<unknown>
      setispedding(true)
      if (!supplierId) {
        res = await addSupplier({ ...params }).finally(() => setispedding(false))
      } else {
        params.cooperateStartDate = detailInfo.cooperateStartDate
        params.supplierClassificationCodeName = detailInfo.supplierClassificationCodeName
        params.supplierClassificationCode = detailInfo.supplierClassificationCode
        res = await editSupplier({ ...params, supplierId }).finally(() => setispedding(false))
      }
      if (res.code === 200) {
        setisEdit(false)
        message.success('操作成功')
        if (!supplierId) {
          navigate('/supplier/create/list')
        } else {
          getDetail()
        }
      }
    })
  }
  const getProductClassConfig = async (type: 1 | 2 | 3 | 4 = 1) => {
    const res = await getProductClassConfigByType<{
      className: string
      classConfigId: string | number
    }>({ type, auth: 1 })
    const classIdOptions =
      res?.data?.map((item) => {
        return {
          label: item.className,
          value: item.classConfigId + '',
        }
      }) || []
    setclassIdOptions(classIdOptions)
  }
  const onValuesFormChange = (changedValues: any) => {
    onValuesChange(
      changedValues,
      [
        'supplierName',
        'supplierShortName',
        'contactName',
        'contactPhone',
        'contactMail',
        'contactAddress',
        'legalPerson',
        'legalContactPhone',
      ],
      FormSupplier,
    )
  }
  const onDownload = (info: string) => {
    downloadByUrl(info)
  }
  const handleDetailFactory = (
    sourceList: IDesListType,
    targetInfo: any,
    set: React.Dispatch<React.SetStateAction<IDesListType>>,
  ) => {
    const res = sourceList?.map((item) => {
      if (typeof item.format === 'function') {
        return {
          ...item,
          content: item.format(targetInfo),
        }
      } else {
        return {
          ...item,
          content: targetInfo[item.key + ''] || '-',
        }
      }
    })
    set(res)
  }
  return (
    <DetailContainer
      className="supplier_edit_page"
      footer={
        !supplierId && (
          <Space>
            <Button type="primary" onClick={() => startEdit(setisbaseinfoEdit)} loading={ispedding}>
              保存
            </Button>
          </Space>
        )
      }
    >
      <Descriptions
        title="基础信息"
        list={isbaseinfoEdit ? [] : baseinfoList}
        extra={
          <Space>
            {supplierId && (
              <PermissionButton
                permission="editSupplier"
                loading={ispedding}
                type="primary"
                onClick={async () => {
                  if (isbaseinfoEdit) {
                    startEdit(setisbaseinfoEdit)
                  } else {
                    setisbaseinfoEdit(true)
                  }
                }}
              >
                {isbaseinfoEdit ? '保存修改' : '编辑'}
              </PermissionButton>
            )}
            {supplierId && isbaseinfoEdit ? (
              <Button
                onClick={() => {
                  setisbaseinfoEdit(false)
                }}
              >
                取消
              </Button>
            ) : null}
          </Space>
        }
      >
        <EditFormInline
          className="sep_forminline_style"
          editConfig={useFormBase({
            DICTDATA,
            classIdOptions,
            CooperateStatusOptions,
            detailInfo,
            isEdit: !!supplierId,
            cooperateStatus,
          })}
          form={FormSupplier}
          onValuesChange={onValuesFormChange}
          initialValues={{ cooperateStartDate: dayjs(), cooperateEndDate: dayjs() }}
        />
      </Descriptions>
      <Descriptions
        title="供应商配置"
        extra={
          <Space>
            {supplierId && (
              <PermissionButton
                permission="editSupplier"
                loading={ispedding}
                type="primary"
                onClick={async () => {
                  if (isconfigEdit) {
                    startEdit(setisconfigEdit)
                  } else {
                    setisconfigEdit(true)
                  }
                }}
              >
                {isconfigEdit ? '保存修改' : '编辑'}
              </PermissionButton>
            )}
            {supplierId && isconfigEdit ? (
              <Button
                onClick={() => {
                  setisconfigEdit(false)
                }}
              >
                取消
              </Button>
            ) : null}
          </Space>
        }
      >
        <Form form={FormSupplier} className="ckbox_box_wrap" layout="horizontal" onValuesChange={onValuesFormChange}>
          <Form.Item name="qcStatus" valuePropName="checked">
            <Checkbox disabled={!isconfigEdit} className="ckbox_box">
              必须执行尾查QC
            </Checkbox>
          </Form.Item>
          <Form.Item name="scanStatus" valuePropName="checked">
            <Checkbox disabled={!isconfigEdit} className="ckbox_box">
              无需扫码装箱
            </Checkbox>
          </Form.Item>
          <Form.Item name="autoShipStatus" valuePropName="checked">
            <Checkbox disabled={!isconfigEdit} className="ckbox_box">
              发货自动审核
            </Checkbox>
          </Form.Item>
          <Form.Item name="aQuotation" valuePropName="checked">
            <Checkbox disabled={!isconfigEdit} className="ckbox_box">
              A模式报价
            </Checkbox>
          </Form.Item>
          <Form.Item className="ckbox_box ckbox_box_spec">
            <Form.Item name="inStore" valuePropName="checked">
              <Checkbox
                disabled={!isconfigEdit}
                onChange={(event) => {
                  if (!event.target.checked) {
                    FormSupplier.setFieldValue('returnDayNum', null)
                  } else {
                    FormSupplier.setFieldValue('returnDayNum', 1)
                  }
                }}
              ></Checkbox>
            </Form.Item>
            <div className="ckbox_box_flex" style={{ color: isconfigEdit ? '#4495f0' : 'rgb(0 0 0 / 25%)' }}>
              <span>入库</span>
              <Form.Item name="returnDayNum">
                <InputNumber
                  className="ckbox_input_style"
                  precision={0}
                  min={1}
                  disabled={!isconfigEdit}
                  onChange={(val) => {
                    console.log(val, 'event')
                    FormSupplier.setFieldValue('inStore', !!val)
                  }}
                ></InputNumber>
              </Form.Item>
              <span>天内，供应商允许退货</span>
            </div>
          </Form.Item>
          <Form.Item name="firstOrderMustQuotation" valuePropName="checked">
            <Checkbox disabled={!isconfigEdit} className="ckbox_box">
              首单必须报价
            </Checkbox>
          </Form.Item>
          <Form.Item name="reorderMustQuotation" valuePropName="checked">
            <Checkbox disabled={!isconfigEdit} className="ckbox_box">
              返单必须报价
            </Checkbox>
          </Form.Item>
          <Form.Item name="settlementUnitPrice" valuePropName="checked">
            <Checkbox disabled={!isconfigEdit} className="ckbox_box">
              填写结算单价
            </Checkbox>
          </Form.Item>
          <div
            className="ckbox_box"
            style={{
              display: 'flex',
              alignItems: 'center',
              gap: 8,
              minWidth: 180,
              color: isconfigEdit ? '#4495f0' : 'rgb(0 0 0 / 25%)',
            }}
          >
            <span>QC人员：</span>
            {!isconfigEdit ? (
              <span>{detailInfo?.qcDefaultUserName || '-'}</span>
            ) : (
              <Form.Item name="qcDefaultUserWorkId">
                <Select
                  disabled={!isconfigEdit}
                  placeholder="请选择"
                  style={{ width: 150, height: 26, lineHeight: 26 }}
                  options={UserOptions}
                  popupMatchSelectWidth={false}
                  showSearch
                  allowClear
                  optionFilterProp="label"
                  filterOption={false}
                  onSearch={handleSearchUser}
                  notFoundContent={<Empty description="请输入内容搜索" image={Empty.PRESENTED_IMAGE_SIMPLE} />}
                ></Select>
              </Form.Item>
            )}
          </div>
        </Form>
      </Descriptions>
      <Descriptions
        title="联络方式"
        list={isConcatEdit ? [] : concatinfoList}
        extra={
          <Space>
            {supplierId && (
              <PermissionButton
                permission="editSupplier"
                loading={ispedding}
                type="primary"
                onClick={async () => {
                  if (isConcatEdit) {
                    await FormSupplier.validateFields()
                    startEdit(setisConcatEdit)
                  } else {
                    setisConcatEdit(true)
                  }
                }}
              >
                {isConcatEdit ? '保存修改' : '编辑'}
              </PermissionButton>
            )}
            {supplierId && isConcatEdit ? (
              <Button
                onClick={() => {
                  setisConcatEdit(false)
                }}
              >
                取消
              </Button>
            ) : null}
          </Space>
        }
      >
        <EditFormVertical
          className="sep_formvertical_style"
          editConfig={useFormInfo({ AreaOptions, loadAreaData, detailInfo })}
          form={FormSupplier}
          onValuesChange={onValuesFormChange}
        />
      </Descriptions>
      <Descriptions
        title="合同信息"
        extra={
          <Space>
            {supplierId && (
              <PermissionButton
                permission="editSupplier"
                loading={ispedding}
                type="primary"
                onClick={async () => {
                  if (isuploadEdit) {
                    await FormSupplier.validateFields()
                    startEdit(setisuploadEdit)
                  } else {
                    setisuploadEdit(true)
                  }
                }}
              >
                {isuploadEdit ? '保存修改' : '编辑'}
              </PermissionButton>
            )}
            {supplierId && isuploadEdit ? (
              <Button
                onClick={() => {
                  setisuploadEdit(false)
                }}
              >
                取消
              </Button>
            ) : null}
          </Space>
        }
      >
        {isuploadEdit ? (
          <Form className="upload_file_wrap" form={FormSupplier} layout="vertical" onValuesChange={onValuesFormChange}>
            <Form.Item label="合同到期时间" name="contractExpTime">
              <DatePicker style={{ width: 300 }}></DatePicker>
            </Form.Item>
            <Form.Item label="合同附件" name="fileId">
              <UploadFile></UploadFile>
            </Form.Item>
            <Form.Item label="公章备案" name="sealUrl">
              <Upload max={1}></Upload>
            </Form.Item>
          </Form>
        ) : (
          <div className="upload_infos_bysupplier">
            <div>
              <div style={{ marginBottom: 6, color: 'var(--color-text-4)' }}>合同到期时间</div>
              {detailInfo?.contractExpTime ? detailInfo?.contractExpTime : '-'}
            </div>
            <div>
              <div style={{ marginBottom: 6, color: 'var(--color-text-4)' }}>合同附件</div>
              {detailInfo?.fileId ? (
                <Space size={'large'}>
                  {detailInfo?.fileId?.split(',').map((item: string) => {
                    return (
                      <Typography.Link key={item} onClick={() => onDownload(item)}>
                        {getNameByOwnUrl(item)}
                      </Typography.Link>
                    )
                  })}
                </Space>
              ) : (
                '-'
              )}
            </div>
            <div>
              <div>
                <div style={{ marginBottom: 6, color: 'var(--color-text-4)' }}>公章备案</div>
                {detailInfo?.sealUrl ? <Upload disabled value={detailInfo?.sealUrl}></Upload> : '-'}
              </div>
            </div>
          </div>
        )}
      </Descriptions>
    </DetailContainer>
  )
}
export default Index
